package com.word.web.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Random;

@Service
public class JsonFileReaderService {

    private static final Random random = new Random();

    @Value("classpath:static/idiom.json")
    private Resource jsonResource;
    private JsonNode jsonNode;

    private void readJsonFile() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        jsonNode = mapper.readTree(jsonResource.getInputStream());
    }

    public JsonNode getNode() throws IOException {
        if (jsonNode == null) {
            readJsonFile();
        }
        // 获取随机索引
        int randomIndex = random.nextInt(jsonNode.size());
        return jsonNode.get(randomIndex);
    }
}
